using System;
using System.Collections.Generic;
using System.IO;

namespace Silvery.Data
{
    public class NTableDataReader
    {
        /// <summary>
        /// 数据字典
        /// </summary>
        protected Dictionary<string, Dictionary<string, string>> datadic = new Dictionary<string, Dictionary<string,string>>();
        /// <summary>
        /// 从内存中读取数据
        /// </summary>
        /// <param name="stream"></param>
        public void Load(Stream stream)
        {
            StreamReader reader = new StreamReader(stream);
            var firstLine = reader.ReadLine();
            char[] comma = { '\t' };
            var field = firstLine.Split(comma, StringSplitOptions.None);
            while (reader.Peek() != -1)
            {
                string strLine = reader.ReadLine();
                string[] strs = strLine.Split(comma, StringSplitOptions.None);
                var id = strs[0];
                if (id != "")
                {
                    if (datadic.ContainsKey(id))
                    {
                        for (int i = 0; i < strs.Length; i++)
                        {
                            var _field = field[i];
                            if (_field == "")
                                _field = "空" + i.ToString();
                            if (datadic[id].ContainsKey(_field))
                            {
                                datadic[id][_field] = strs[i];
                            }
                            else
                                datadic[id].Add(_field, strs[i]);
                        }
                    }
                    else
                    {
                        Dictionary<string, string> subdic = new Dictionary<string, string>();
                        for (int i = 0; i < strs.Length; i++)
                        {
                            if (field[i] == "")
                                field[i] = "空" + i.ToString();
                            subdic.Add(field[i], strs[i]);
                        }
                        datadic.Add(id, subdic);
                    }
                }
            }
        }

        /// <summary>
        /// 从key和field取出数据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="field"></param>
        /// <returns></returns>

        public string this[string key, string field]
        {
            get
            {
                if (datadic.ContainsKey(key))
                    if (datadic[key].ContainsKey(field))
                        if (datadic[key][field] != "")
                            return datadic[key][field];
                        else
                            return "";
                    else
                        return "";
                else
                    return "";
            }
            
        }

    
    }
}
